package SubjectTree.Two;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import Utility.TreeNode;

public class BinaryTreePaths {

/**
 * 难度：简单
 * 
 * 257. 二叉树的所有路径
 * 	给定一个二叉树，返回所有从根节点到叶子节点的路径。
 * 	
 * 说明: 叶子节点是指没有子节点的节点。
 * 	
 * 示例:
 * 	输入:
 * 	   1
 * 	 /   \
 * 	2     3
 * 	 \
 * 	  5
 * 	输出: ["1->2->5", "1->3"]
 * 	解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
 *
 * */
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BinaryTreePaths btp = new BinaryTreePaths();
		TreeNode root = TreeNode.MkTree("[1,2,3,null,5]");
		System.out.println(btp.binaryTreePaths(root));
	}
	//自己写（迭代）
	public List<String> binaryTreePaths(TreeNode root) {
		List<String> paths = new ArrayList<String>();
		if(root == null) return paths;
		
		Deque<TreeNode> deque = new LinkedList<>();
		Queue<String> pathQueue = new LinkedList<String>();
		
		deque.offer(root);
		pathQueue.offer(Integer.toString(root.val));
		
		while(!deque.isEmpty()) {
			TreeNode node = deque.poll();
			String path = pathQueue.poll();
			
			if(node.left==null&&node.right==null) {
				paths.add(path);
			}else {
				if(node.left!=null) {
					deque.offer(node.left); 
					pathQueue.offer(new StringBuilder(path).append("->").append(node.left.val).toString());
				}
				
				if(node.right!=null) {
					deque.offer(node.right); 
					pathQueue.offer(new StringBuilder(path).append("->").append(node.right.val).toString());
				}
			}
		}
		return paths;
	}
	
	//自己写（递归）
	public List<String> binaryTreePaths_1(TreeNode root) {
		List<String> result = new ArrayList<>();
		List<Integer> path = new ArrayList<>();
		if(root==null)return result;
		traversal(root, path, result);
		return result;
	}
	//第一步：确定递归函数函数参数以及返回值
	public void traversal(TreeNode cur, List<Integer> path, List<String> result) {
		path.add(cur.val);
		//第二步：确定递归终止条件
		if(cur.left==null&&cur.right==null) {// 遇到叶子节点
			String sPath = "";
			for(int i=0;i<path.size()-1;i++) {// 将path里记录的路径转为string格式
				sPath+=path.get(i).toString();
				sPath+="->";
			}
			sPath+=path.get(path.size()-1).toString();// 记录最后一个节点（叶子节点）
			result.add(sPath);// 收集一个路径
			
			return;
		}
		//第三步：确定单层递归逻辑
		if(cur.left!=null) {
			traversal(cur.left,path,result);
			//回溯和递归是一一对应的，有一个递归，就要有一个回溯
			path.remove(path.size()-1);// 回溯
		}
		if(cur.right!=null) {
			traversal(cur.right,path,result);
			path.remove(path.size()-1);// 回溯
		}
	}
	
	//方法一：深度优先搜索
	public List<String> binaryTreePaths1(TreeNode root) {
		List<String> paths = new ArrayList<String>();
		constructPaths(root, "", paths);
		return paths;
    }
	public void constructPaths(TreeNode root, String path, List<String> paths) {
        if (root != null) {
            StringBuffer pathSB = new StringBuffer(path);
            pathSB.append(Integer.toString(root.val));
            if (root.left == null && root.right == null) {  // 当前节点是叶子节点
                paths.add(pathSB.toString());  // 把路径加入到答案中
            } else {
                pathSB.append("->");  // 当前节点不是叶子节点，继续递归遍历
                constructPaths(root.left, pathSB.toString(), paths);
                constructPaths(root.right, pathSB.toString(), paths);
            }
        }
    }
	//方法二：广度优先搜索
	public List<String> binaryTreePaths2(TreeNode root) {
        List<String> paths = new ArrayList<String>();
        if (root == null) {
            return paths;
        }
        Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
        Queue<String> pathQueue = new LinkedList<String>();

        nodeQueue.offer(root);
        pathQueue.offer(Integer.toString(root.val));

        while (!nodeQueue.isEmpty()) {
            TreeNode node = nodeQueue.poll(); 
            String path = pathQueue.poll();

            if (node.left == null && node.right == null) {
                paths.add(path);
            } else {
                if (node.left != null) {
                    nodeQueue.offer(node.left);
                    pathQueue.offer(new StringBuffer(path).append("->").append(node.left.val).toString());
                }

                if (node.right != null) {
                    nodeQueue.offer(node.right);
                    pathQueue.offer(new StringBuffer(path).append("->").append(node.right.val).toString());
                }
            }
        }
        return paths;
    }
}
